package com.twang.stock.task.old;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.entity.CompanyCodeInfo;
import com.twang.stock.entity.StockMoneyIn;
import com.twang.stock.mapper.CompanyCodeInfoMapper;
import com.twang.stock.mapper.StockMoneyInMapper;
import com.twang.stock.common.CommonUtils;
import com.twang.stock.service.jinyan.HolidayService;
import com.twang.stock.email.SendmailService;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import com.twang.stock.utils.clawer.HttpHelper;
import com.twang.stock.utils.date.HolidayCopy;
import org.assertj.core.util.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 更新主力资金情况  每日14点50更新
 */
@Slf4j
@Service
public class StockMoneyInTask extends BaseTask{
    private static final String USER_AGENT = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T)  AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36";
    private static final String COOKIE = "_gat=1; nsfw-click-load=off; gif-click-load=on;_ga=GA1.2.1861846600.1423061484";
    @Resource
    private StockMoneyInMapper stockMoneyInMapper;
    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;
    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;
    @Autowired
    private SendmailService sendmailService;
    @Autowired
    private HolidayService holidhayService;

 //  @Scheduled(cron = "0 50 16 * * ?")
    public void excute() {
        try {
            if (!isWork()) {
                return;
            }
            Example example=new Example(CompanyCodeInfo.class);
            Example.Criteria criteria= example.createCriteria();
            criteria.andGreaterThan("tradingVolume",5);
            List<CompanyCodeInfo> stockList = companyCodeInfoMapper.selectByExample(example);
            //
            stockList.forEach(item -> {
                asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                    try {
                        log.info(" 更新主力资金  start code={}", item);
                        moneyInHistory(item.getCompanyCode());
                        log.info(" 更新主力资金  end code={}", item);
                    } catch (Exception e) {
                        log.info(" 更新主力资金异常 e={}", e);
                    }
                });
            });
            sendmailService.insertEvent(CommonUtils.TASK_NAME_RULE_3, CommonUtils.SUCCESS_MESSAGE,"SUCCESS",CommonUtils.RULE_SUCCESS);
        } catch (Exception e) {
            sendmailService.insertEvent(CommonUtils.TASK_NAME_RULE_3, CommonUtils.FAILE_MESSAGE + JSONObject.toJSONString(e),"ERROR",CommonUtils.RULE_EXCEPTION);
        }
       updateTotalAmount();
       updateTotalAmountDays();
       //更新资金排名
       excutePosition(Lists.newArrayList(holidhayService.getDayByNum(0)));
       //更新资金连续天数
       updatePosition(null);
    }

    /**
     * 执行名次处理
     */
    public void excutePosition(List<String> dates) {
        if(CollectionUtils.isEmpty(dates)){
            return;
        }
        Example example = new Example(CompanyCodeInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andGreaterThan("tradingVolume", 5);
        List<CompanyCodeInfo> stockList = companyCodeInfoMapper.selectByExample(example);
        //查询list集合
        stockList.forEach(companyCodeInfo -> {
            dates.forEach(date -> {
                asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                    Example exampleStockMoneyIn = new Example(StockMoneyIn.class);
                    Example.Criteria criteriaStockMoneyIn = exampleStockMoneyIn.createCriteria();
                    criteriaStockMoneyIn.andEqualTo("date", date);
                    criteriaStockMoneyIn.andEqualTo("stockName", companyCodeInfo.getCompanyCode());
                    exampleStockMoneyIn.orderBy("date").desc();
                    List<StockMoneyIn> stockMoneyIns  = stockMoneyInMapper.selectByExample(exampleStockMoneyIn);
                    //遍历所有的个股
                    stockMoneyIns.forEach(stockMoneyIn -> {
                        // stockMoneyInMapper.updatePoistTion(stockMoneyIn.getDate(), stockMoneyIn.getStockName());
                        int position = stockMoneyInMapper.getPosiTion(stockMoneyIn.getDate(), stockMoneyIn.getStockName());
                        stockMoneyIn.setPosition(position);
                        //
                        String lastPositionDate = stockMoneyInMapper.getSecondDate(stockMoneyIn.getDate(), stockMoneyIn.getStockName());
                        int lastPosition = stockMoneyInMapper.getPosiTion(lastPositionDate, stockMoneyIn.getStockName());
                        stockMoneyIn.setLastPosition(lastPosition);
                        //
                        int upDownPosition=lastPosition-position;
                        stockMoneyIn.setUpDownPosition(upDownPosition);
                        stockMoneyInMapper.updateByPrimaryKey(stockMoneyIn);
                        log.info(" {} 执行完成！", stockMoneyIn.getStockName());
                    });
                    int numbers = 0;
                    StockMoneyIn stockMoneyInLast = stockMoneyIns.get(0);
                    for (StockMoneyIn stockMoneyIn : stockMoneyIns) {
                        if (stockMoneyIn.getUpDownPosition() > 0) {
                            numbers++;
                        } else {
                            break;
                        }
                    }
                    stockMoneyInLast.setPositionInDates(numbers);
                    stockMoneyInMapper.updateByPrimaryKey(stockMoneyInLast);
                });
            });
        });
    }
    public void updatePosition(List<String> dates) {
        Example example = new Example(CompanyCodeInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andGreaterThan("tradingVolume", 5);
        List<CompanyCodeInfo> stockList = companyCodeInfoMapper.selectByExample(example);
        //查询list集合
        stockList.forEach(companyCodeInfo -> {
            Example exampleStockMoneyIn = new Example(StockMoneyIn.class);
            Example.Criteria criteriaStockMoneyIn = exampleStockMoneyIn.createCriteria();
            criteriaStockMoneyIn.andEqualTo("stockName", companyCodeInfo.getCompanyCode());
            exampleStockMoneyIn.orderBy("date").desc();
            List<StockMoneyIn> stockMoneyIns = stockMoneyInMapper.selectByExample(exampleStockMoneyIn);
            int numbers = 0;
            for (StockMoneyIn stockMoneyIn : stockMoneyIns) {
                String lastPositionDate = stockMoneyInMapper.getSecondDate(stockMoneyIn.getDate(), stockMoneyIn.getStockName());
                int lastPosition = stockMoneyInMapper.getPosiTion(lastPositionDate, stockMoneyIn.getStockName());
                if (stockMoneyIn.getPosition() - lastPosition < 0) {
                    numbers++;
                } else {
                    break;
                }
            }
            StockMoneyIn stockMoneyInLast = stockMoneyIns.get(0);
            stockMoneyInLast.setPositionInDates(numbers);
            stockMoneyInMapper.updateByPrimaryKey(stockMoneyInLast);
        });
    }


    /**
     * 更新资金总流入
     */
    public void updateTotalAmount() {
        List<CompanyCodeInfo> stockList = companyCodeInfoMapper.selectAll();
        stockList.forEach(companyCodeInfo -> {
            Example example = new Example(StockMoneyIn.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("stockName", companyCodeInfo.getCompanyCode());
            example.orderBy("date").asc();
            List<StockMoneyIn> list = stockMoneyInMapper.selectByExample(example);
            BigDecimal amount = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(list)) {
                log.info("资金最新日期： code={}  date={}", companyCodeInfo.getCompanyCode(), list.get(list.size()-1).getDate());
                // amount=list.get(0).getTd3();
                for (StockMoneyIn item : list) {
                    amount = amount.add(item.getTd3());
                    item.setTotoalAmount(amount);
                }
            } else {
                log.info("未查询到资金列表：name= {}", companyCodeInfo.getCompanyCode());
            }
            companyCodeInfo.setTotalMoneyIn(amount);
            companyCodeInfo.setUpdateTime(HolidayCopy.getRealToday());
            companyCodeInfo.setModifyTime(new Date());
            companyCodeInfoMapper.updateByPrimaryKey(companyCodeInfo);
            log.info("主力资金更新完成：name= {}  资金={}万元", companyCodeInfo.getCompanyCode(),companyCodeInfo.getTotalMoneyIn());
        });

    }

    /**
     * 更新资金连续流入天数
     */
    public void updateTotalAmountDays() {
        List<CompanyCodeInfo> stockList = companyCodeInfoMapper.selectAll();
        stockList.forEach(companyCodeInfo -> {
            Example example = new Example(StockMoneyIn.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("stockName", companyCodeInfo.getCompanyCode());
            example.orderBy("date").desc();
            List<StockMoneyIn> list = stockMoneyInMapper.selectByExample(example);
            BigDecimal amount = BigDecimal.ZERO;
            Integer day=0;
            if (!CollectionUtils.isEmpty(list)) {
                // amount=list.get(0).getTd3();
                for (StockMoneyIn item : list) {
                   if(item.getTd3().compareTo(BigDecimal.ZERO)==1){
                       day++;
                   }else{
                       break;
                   }
                }
            }
            companyCodeInfo.setTotalMoneyInDays(day);
            companyCodeInfo.setUpdateTime(HolidayCopy.getRealToday());
            companyCodeInfo.setModifyTime(new Date());
            companyCodeInfoMapper.updateByPrimaryKey(companyCodeInfo);
            log.info("主力资金更新完成：name= {}  资金={}万元", companyCodeInfo.getCompanyCode(),companyCodeInfo.getTotalMoneyIn());
        });

    }

    public void moneyInHistory(String stock) throws Exception {
        if (StringUtils.isEmpty(stock)) {
            throw new Exception("代码不能为空！");
        }
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        StringBuffer url = new StringBuffer("").append("http://stockpage.10jqka.com.cn/").append(stock.substring(2, 8)).append("/funds/");
        String urlToReq = "";
        try {
           Thread.sleep(1000);
            // 停留一秒后开始任务
            // 发送请求，并执行
            String htmlForStock = HttpHelper.getHtmlStrByUrl(url.toString(), httpClient, COOKIE, USER_AGENT);
            // 网页内容解析
            log.info("该网页存在,正在解析:{}", urlToReq);
            Document doc = Jsoup.parse(htmlForStock);
            // 获取table表的行集合元素
            Elements trs;
            try {
                 trs = doc.getElementById("history_table_free").select("tr");
            }catch (Exception e){
                log.info("{} ",e);
                throw e;
            }
            //   SharePo sharePo = new SharePo();
            //只更新当日得资金
            for (int j = 2; j <trs.size(); j++) {
                StockMoneyIn dataDto = new StockMoneyIn();
                dataDto.setStockName(stock);
                Elements tds = trs.get(j).select("td");
                // sharePo = new SharePo();
                //日期
                dataDto.setDate(tds.get(0).html());

                //收盘价
                String td1 = tds.get(1).html();
                dataDto.setTd1(null == td1 ? BigDecimal.ZERO : new BigDecimal(td1));
                //涨跌幅
                String td2 = tds.get(2).html();
                dataDto.setTd2(td2);
                //资金净流入
                String td3 = tds.get(3).html();
                dataDto.setTd3(null == td3 ? BigDecimal.ZERO : new BigDecimal(td3));
                //5日主力净额
                String td4 = tds.get(4).html();
                dataDto.setTd4(null == td4 ? BigDecimal.ZERO : new BigDecimal(td4));

                //大单(主力)	- 净额
                String td5 = tds.get(5).html();
                dataDto.setTd5(null == td5 ? BigDecimal.ZERO : new BigDecimal(td5));

                //大单(主力)	- 净占比
                String td6 = tds.get(6).html();
                dataDto.setTd6(td6);
                //中单	-净额
                String td7 = tds.get(7).html();
                dataDto.setTd7(null == td7 ? BigDecimal.ZERO : new BigDecimal(td7));

                //中单	-净占比
                String td8 = tds.get(8).html();
                dataDto.setTd8(td8);

                //小单	-净额
                String td9 = tds.get(9).html();
                dataDto.setTd9(null == td9 ? BigDecimal.ZERO : new BigDecimal(td9));

                //小单	-净占比
                String td10 = tds.get(10).html();
                dataDto.setTd10(td10);
                dataDto.setCreateTime(new Date());
                dataDto.setModifyTime(new Date());
                //
                log.info(" 主力资金 : {}", JSONObject.toJSONString(dataDto));
                StockMoneyIn param = new StockMoneyIn();
                param.setStockName(dataDto.getStockName());
                param.setDate(dataDto.getDate());
                if (stockMoneyInMapper.select(param).size() > 0) {
                    Example example = new Example(StockMoneyIn.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("stockName", dataDto.getStockName());
                    criteria.andEqualTo("date", dataDto.getDate());
                    stockMoneyInMapper.updateByExample(dataDto, example);
                } else {
                    stockMoneyInMapper.insert(dataDto);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        // HttpClient 超时配置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
                .setConnectionRequestTimeout(6000).setConnectTimeout(6000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
        StringBuffer url = new StringBuffer("").append("http://q.10jqka.com.cn/index/index/board/all/field/zdf/order/desc/page/1/ajax/1/");
        String urlToReq = "";
        try {
            // 停留一秒后开始任务
            // 发送请求，并执行
            String htmlForStock = HttpHelper.getHtmlStrByUrl(url.toString(), httpClient, COOKIE, USER_AGENT);
            // 网页内容解析
            log.info("该网页存在,正在解析:{}", urlToReq);
            Document doc = Jsoup.parse(htmlForStock);
            // 获取table表的行集合元素
            Elements trs = doc.getElementById("maincont").select("tr");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}